<template>
  <div id="UserManagePage" class="user-manage-container">
    <!-- 搜索卡片区域 -->
    <a-card title="用户筛选" class="search-card" :bordered="false">
      <a-form
        :model="searchParams"
        layout="inline"
        @finish="doSearch"
        class="search-form"
      >
        <a-form-item label="账号" class="form-item">
          <a-input
            v-model:value="searchParams.userAccount"
            placeholder="请输入账号"
            allow-clear
            class="search-input"
          >
            <template #prefix>
              <UserOutlined />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item label="用户名" class="form-item">
          <a-input
            v-model:value="searchParams.userName"
            placeholder="请输入用户名"
            allow-clear
            class="search-input"
          >
            <template #prefix>
              <IdcardOutlined />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item class="form-item">
          <a-space>
            <a-button
              type="primary"
              html-type="submit"
              class="search-btn"
            >
              <template #icon>
                <SearchOutlined />
              </template>
              搜索
            </a-button>
            <a-button @click="handleReset" class="reset-btn">
              <template #icon>
                <RedoOutlined />
              </template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 用户列表卡片区域 -->
    <a-card title="用户列表" class="table-card" :bordered="false">
      <div class="table-header">
        <div class="table-title">
          <TeamOutlined class="title-icon" />
          <span>用户信息</span>
        </div>
        <div class="table-actions">
          <a-button
            type="primary"
            @click="handleExport"
            class="action-btn"
          >
            <template #icon>
              <ExportOutlined />
            </template>
            导出
          </a-button>
        </div>
      </div>

      <a-table
        :columns="columns"
        :data-source="dataList"
        :pagination="pagination"
        @change="doTableChange"
        :loading="loading"
        :scroll="{ x: 1200 }"
        row-key="id"
        class="user-table"
      >
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.dataIndex === 'index'">
            <span class="row-index">{{ index + 1 }}</span>
          </template>

          <template v-else-if="column.dataIndex === 'userAvatar'">
            <div class="avatar-container">
              <a-avatar
                :src="record.userAvatar"
                :size="48"
                class="user-avatar"
                :alt="record.userName"
              >
                <template v-if="!record.userAvatar" #icon>
                  <UserOutlined />
                </template>
              </a-avatar>
            </div>
          </template>

          <template v-else-if="column.dataIndex === 'userRole'">
            <div class="user-role">
              <a-tag
                :color="getRoleColor(record.userRole)"
                class="role-tag"
              >
                <template #icon>
                  <CrownOutlined v-if="record.userRole === 'admin'" />
                  <UserOutlined v-else-if="record.userRole === 'user'" />
                  <StopOutlined v-else />
                </template>
                {{ getRoleText(record.userRole) }}
              </a-tag>
            </div>
          </template>

          <template v-else-if="column.dataIndex === 'createTime'">
            <span class="create-time">
              {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
            </span>
          </template>

          <template v-else-if="column.dataIndex === 'userProfile'">
            <div class="user-profile">
              {{ record.userProfile || '暂无简介' }}
            </div>
          </template>

          <template v-else-if="column.key === 'action'">
            <div class="action-buttons">
              <a-tooltip title="编辑用户">
                <a-button
                  type="link"
                  @click="() => showEditDrawer(record)"
                  class="edit-btn"
                >
                  <template #icon>
                    <EditOutlined />
                  </template>
                  编辑
                </a-button>
              </a-tooltip>

              <a-popconfirm
                title="确定要删除这个用户吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="() => doDelete(record.id)"
                placement="topRight"
              >
                <a-tooltip title="删除用户">
                  <a-button
                    type="link"
                    danger
                    class="delete-btn"
                  >
                    <template #icon>
                      <DeleteOutlined />
                    </template>
                    删除
                  </a-button>
                </a-tooltip>
              </a-popconfirm>
            </div>
          </template>
        </template>

        <template #emptyText>
          <div class="empty-state">
            <a-empty
              image="/api/placeholder/200/150"
              description="暂无用户数据"
            >
              <a-button type="primary" @click="getUserList">
                重新加载
              </a-button>
            </a-empty>
          </div>
        </template>
      </a-table>
    </a-card>

    <!-- 编辑用户抽屉 -->
    <a-drawer
      v-model:visible="editDrawerVisible"
      title="编辑用户信息"
      :width="600"
      placement="right"
      :footer-style="{ textAlign: 'right', padding: '16px 24px' }"
      @close="handleEditCancel"
      class="edit-drawer"
      :z-index="1001"
    >
      <a-form
        ref="editFormRef"
        :model="editForm"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        :rules="editFormRules"
        layout="horizontal"
        class="edit-form"
      >
        <a-form-item label="用户ID" name="id">
          <a-input
            v-model:value="editForm.id"
            disabled
            class="disabled-input"
          />
        </a-form-item>

        <a-form-item label="账号" name="userAccount" required>
          <a-input
            v-model:value="editForm.userAccount"
            placeholder="请输入账号"
            allow-clear
            class="form-input"
          >
            <template #prefix>
              <UserOutlined />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item label="用户名" name="userName" required>
          <a-input
            v-model:value="editForm.userName"
            placeholder="请输入用户名"
            allow-clear
            class="form-input"
          >
            <template #prefix>
              <IdcardOutlined />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item label="头像URL" name="userAvatar">
          <div class="avatar-upload-section">
            <a-input
              v-model:value="editForm.userAvatar"
              placeholder="请输入头像URL"
              allow-clear
              class="avatar-input"
            >
              <template #prefix>
                <PictureOutlined />
              </template>
            </a-input>
            <div class="avatar-preview" v-if="editForm.userAvatar">
              <a-image
                :src="editForm.userAvatar"
                :width="80"
                :height="80"
                :preview="false"
                class="preview-image"
                fallback="/api/placeholder/80/80"
              />
            </div>
          </div>
        </a-form-item>

        <a-form-item label="用户简介" name="userProfile">
          <a-textarea
            v-model:value="editForm.userProfile"
            placeholder="请输入用户简介"
            :rows="3"
            show-count
            :maxlength="200"
            class="profile-textarea"
          />
        </a-form-item>

        <a-form-item label="用户角色" name="userRole" required>
          <a-select
            v-model:value="editForm.userRole"
            placeholder="请选择用户角色"
            class="role-select"
          >
            <a-select-option value="admin">
              <CrownOutlined /> 管理员
            </a-select-option>
            <a-select-option value="user">
              <UserOutlined /> 普通用户
            </a-select-option>
            <a-select-option value="ban">
              <StopOutlined /> 封禁
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="创建时间">
          <a-input
            :value="dayjs(editForm.createTime).format('YYYY-MM-DD HH:mm:ss')"
            disabled
            class="disabled-input"
          />
        </a-form-item>
      </a-form>

      <template #footer>
        <a-space>
          <a-button
            :loading="editLoading"
            @click="handleEditCancel"
            class="cancel-btn"
          >
            取消
          </a-button>
          <a-button
            type="primary"
            :loading="editLoading"
            @click="handleEditSubmit"
            class="submit-btn"
          >
            <template #icon>
              <CheckOutlined />
            </template>
            确认
          </a-button>
        </a-space>
      </template>
    </a-drawer>
  </div>
</template>

<script lang="ts" setup>
import { deleteUserUsingPost, listUserVoByPageUsingPost, updateUserUsingPost } from '@/api/userController'
import dayjs from 'dayjs'
import { computed, onMounted, reactive, ref } from 'vue'
import type { FormInstance } from 'ant-design-vue'
import { message } from 'ant-design-vue'
import {
  UserOutlined,
  IdcardOutlined,
  SearchOutlined,
  RedoOutlined,
  TeamOutlined,
  ExportOutlined,
  EditOutlined,
  DeleteOutlined,
  CrownOutlined,
  StopOutlined,
  PictureOutlined,
  CheckOutlined
} from '@ant-design/icons-vue'

// 列定义
const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    width: 60,
    align: 'center' as const
  },
  {
    title: '账号',
    dataIndex: 'userAccount',
    key: 'userAccount',
    width: 120,
    ellipsis: true
  },
  {
    title: '用户名',
    dataIndex: 'userName',
    key: 'userName',
    width: 120,
    ellipsis: true
  },
  {
    title: '头像',
    dataIndex: 'userAvatar',
    key: 'userAvatar',
    width: 80,
    align: 'center' as const
  },
  {
    title: '简介',
    dataIndex: 'userProfile',
    key: 'userProfile',
    width: 200,
    ellipsis: true
  },
  {
    title: '用户角色',
    dataIndex: 'userRole',
    key: 'userRole',
    width: 100,
    align: 'center' as const
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 180
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    align: 'center' as const,
    fixed: 'right' as const
  }
]

const dataList = ref([])
const total = ref(0)
const loading = ref(false)
const editLoading = ref(false)

// 搜索条件
const searchParams = reactive<API.UserQueryRequest>({
  current: 1,
  pageSize: 10,
})

// 编辑表单引用
const editFormRef = ref<FormInstance>()

// 编辑表单数据
const editForm = reactive({
  id: undefined as number | undefined,
  userAccount: '',
  userName: '',
  userAvatar: '',
  userProfile: '',
  userRole: 'user',
  createTime: ''
})

// 编辑表单验证规则
const editFormRules = {
  userAccount: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 20, message: '账号长度在3-20个字符之间', trigger: 'blur' }
  ],
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在2-20个字符之间', trigger: 'blur' }
  ],
  userRole: [
    { required: true, message: '请选择用户角色', trigger: 'change' }
  ]
}

// 编辑抽屉显示状态
const editDrawerVisible = ref(false)

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.current,
    pageSize: searchParams.pageSize,
    total: total.value,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number, range: number[]) =>
      `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
    pageSizeOptions: ['10', '20', '50', '100'],
    size: 'default' as const
  }
})

// 获取用户角色颜色
const getRoleColor = (role: string) => {
  const colorMap = {
    admin: 'green',
    user: 'blue',
    ban: 'red'
  }
  return colorMap[role] || 'default'
}

// 获取用户角色文本
const getRoleText = (role: string) => {
  const textMap = {
    admin: '管理员',
    user: '普通用户',
    ban: '封禁'
  }
  return textMap[role] || '未知'
}

// 获取用户列表
const getUserList = async () => {
  loading.value = true
  try {
    const res = await listUserVoByPageUsingPost(searchParams)
    if (res.data.data && res.data.code === 0) {
      dataList.value = res.data.data.records
      total.value = res.data.data.total
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    message.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 显示编辑抽屉并回填数据
const showEditDrawer = (record: any) => {
  Object.assign(editForm, {
    id: record.id,
    userAccount: record.userAccount,
    userName: record.userName,
    userAvatar: record.userAvatar,
    userProfile: record.userProfile,
    userRole: record.userRole,
    createTime: record.createTime
  })
  editDrawerVisible.value = true
}

// 处理编辑提交
const handleEditSubmit = async () => {
  try {
    // 验证表单
    await editFormRef.value?.validate()

    editLoading.value = true

    const res = await updateUserUsingPost(editForm)
    if (res.data.code === 0 && res.data.data) {
      // 更新成功，刷新列表
      message.success('用户信息更新成功')
      await getUserList()
      editDrawerVisible.value = false
    } else {
      message.error(res.data.message || '更新失败')
    }
  } catch (error) {
    console.error('更新用户信息时发生错误:', error)
    if (error instanceof Error) {
      message.error('表单验证失败，请检查输入')
    }
  } finally {
    editLoading.value = false
  }
}

// 处理编辑取消
const handleEditCancel = () => {
  editDrawerVisible.value = false
  // 重置表单
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }
}

// 切换表格页数
const doTableChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  getUserList()
}

// 删除用户
const doDelete = async (id: number) => {
  try {
    const res = await deleteUserUsingPost({ id })
    if (res.data.code === 0 && res.data.data) {
      message.success('删除成功')
      getUserList()
    } else {
      message.error(res.data.message || '删除失败')
    }
  } catch (error) {
    console.error('删除用户失败:', error)
    message.error('删除用户失败')
  }
}

// 搜索
const doSearch = () => {
  searchParams.current = 1
  getUserList()
}

// 重置搜索条件
const handleReset = () => {
  searchParams.userAccount = ''
  searchParams.userName = ''
  searchParams.current = 1
  getUserList()
}

// 导出功能（示例）
const handleExport = () => {
  message.info('导出功能开发中...')
}

onMounted(() => {
  getUserList()
})
</script>

<style lang="scss" scoped>
.user-manage-container {
  background-color: #f0f2f5;
  min-height: 100vh;

  .search-card {
    margin-bottom: 16px;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

    :deep(.ant-card-head) {
      border-bottom: 1px solid #f0f0f0;
      padding: 12px 16px;
      min-height: auto;

      .ant-card-head-title {
        font-size: 16px;
        font-weight: 600;
        color: #262626;
      }
    }

    :deep(.ant-card-body) {
      padding: 16px;
    }
  }

  .search-form {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;

    .form-item {
      margin-bottom: 0;

      .search-input {
        width: 200px;
      }
    }

    .search-btn, .reset-btn {
      border-radius: 6px;
    }
  }

  .table-card {
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

    :deep(.ant-card-head) {
      border-bottom: 1px solid #f0f0f0;
      padding: 16px;
      min-height: auto;

      .ant-card-head-title {
        font-size: 16px;
        font-weight: 600;
        color: #262626;
      }
    }

    :deep(.ant-card-body) {
      padding: 0;
    }
  }

  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-bottom: 1px solid #f0f0f0;

    .table-title {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 15px;
      font-weight: 500;
      color: #595959;

      .title-icon {
        color: #1890ff;
      }
    }

    .table-actions {
      .action-btn {
        border-radius: 6px;
      }
    }
  }

  .user-table {
    :deep(.ant-table) {
      .ant-table-thead > tr > th {
        background-color: #fafafa;
        color: #595959;
        font-weight: 600;
        padding: 12px 8px;
      }

      .ant-table-tbody > tr > td {
        padding: 12px 8px;
        border-bottom: 1px solid #f0f0f0;
      }

      .ant-table-tbody > tr:hover > td {
        background-color: #f5f5f5;
      }
    }

    .row-index {
      color: #8c8c8c;
      font-weight: 500;
    }

    .avatar-container {
      display: flex;
      justify-content: center;

      .user-avatar {
        border: 2px solid #f0f0f0;
      }
    }

    .user-role {
      display: flex;
      justify-content: center;

      .role-tag {
        border-radius: 12px;
        font-weight: 500;
      }
    }

    .create-time {
      color: #8c8c8c;
      font-size: 13px;
    }

    .user-profile {
      max-width: 200px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      color: #595959;
    }

    .action-buttons {
      display: flex;
      justify-content: center;
      gap: 4px;

      .edit-btn, .delete-btn {
        padding: 4px 8px;
        height: auto;
        border: none;
        box-shadow: none;

        &:hover {
          background-color: #f5f5f5;
        }
      }
    }

    .empty-state {
      padding: 40px 0;
    }
  }

  .edit-drawer {
    :deep(.ant-drawer-header) {
      border-bottom: 1px solid #f0f0f0;
      padding: 16px 24px;

      .ant-drawer-title {
        font-size: 16px;
        font-weight: 600;
        color: #262626;
      }
    }

    :deep(.ant-drawer-body) {
      padding: 24px;
    }

    .edit-form {
      .disabled-input {
        background-color: #fafafa;
        color: #8c8c8c;
      }

      .form-input, .avatar-input, .role-select {
        border-radius: 6px;
      }

      .avatar-upload-section {
        .avatar-preview {
          margin-top: 12px;
          text-align: center;

          .preview-image {
            border-radius: 6px;
            border: 1px solid #f0f0f0;
          }
        }
      }

      .profile-textarea {
        border-radius: 6px;
        resize: vertical;
      }
    }

    .cancel-btn, .submit-btn {
      border-radius: 6px;
      padding: 0 20px;
      height: 36px;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .user-manage-container {
    padding: 16px;

    .search-form {
      flex-direction: column;
      gap: 12px;

      .form-item {
        width: 100%;

        .search-input {
          width: 100%;
        }
      }
    }

    .table-header {
      flex-direction: column;
      gap: 12px;
      align-items: stretch;

      .table-actions {
        display: flex;
        justify-content: flex-end;
      }
    }
  }
}
</style>
